#include "QRONode_P.h"

void QRONode::Private::onOccupyObject(QObject* target){
    auto localId = m_objectIdMap.value(target,NullID);
    if(!localId) return;
    auto remoteId = m_remoteIdMapper.key(localId);

    m_channel->occupyObject(remoteId);
}

void QRONode::Private::onReleaseObject(QObject* target){
    auto localId = m_objectIdMap.value(target,NullID);
    if(!localId) return;
    auto remoteId = m_remoteIdMapper.key(localId);

    if(remoteId != m_channel->ownedObjs()) return;

    m_channel->releaseObject();
}

QObject *QRONode::Private::getOccupiedObject()
{
    auto remoteId = m_channel->ownedObjs();

    if(!remoteId) return NULL;

    return m_objectDataMap[m_remoteIdMapper[remoteId]]->obj;
}

void QRONode::Private::onOwnedObjectChanged(){
    auto remoteId = m_channel->ownedObjs();

    auto localId = m_remoteIdMapper[remoteId];

    if(!localId && !lastOwned)
    {
        return;
    }

    if(localId)
    {
        auto obj = m_objectDataMap[localId];
        _Q->occupiedObject(obj->obj);
    }

    if(lastOwned)
    {
        auto obj = m_objectDataMap[lastOwned];
        _Q->releaseObject(obj->obj);
    }

    lastOwned = localId;
}

bool QRONode::Private::notBelongTo(ObjectID localId)
{
    if(m_channel->ownedObjs() == NullID)
    {
        return true;
    }

    auto occupied = m_remoteIdMapper[m_channel->ownedObjs()];

    auto temp = m_objectDataMap[localId]->obj;

    while (temp) {

        auto id = m_objectIdMap.value(temp);
        if(id == occupied)
        {
            return false;//不确定是否占领，但有可能
        }

        temp = temp->parent();
    }

    return true;
}
